//
//  PPHttpManage.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/10.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "PPHttpManage.h"

static PPHttpManage *httpManege = nil;
@implementation PPHttpManage

+(PPHttpManage *)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!httpManege) {
            httpManege = [[self alloc]init];
        }
    });
    
    return httpManege;
}

+(id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (!httpManege) {
            httpManege = [super allocWithZone:zone];
        }
    }
    return httpManege;
}

-(id)init{
    @synchronized(self)
    {
        if (self = [super init])
        {

            _sessionManager = [AFHTTPSessionManager manager];
            //适配https
//            AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//         //   securityPolicy.allowInvalidCertificates = YES;
//            [securityPolicy setValidatesDomainName:YES];
//            
//            _sessionManager.securityPolicy = securityPolicy;
            
          
            //申明返回的结果是json类型
            _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
            //申明请求的数据是json类型
            _sessionManager.requestSerializer=[AFJSONRequestSerializer serializer];
            
            _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",
                                    @"text/html",@"text/plain",nil];
            
            _sessionManager.requestSerializer.timeoutInterval = 15;

        //  [_sessionManager.securityPolicy setAllowInvalidCertificates:YES];
        }
    }
    
    return self;
}

- (void)requestData:(PPHttpRequest *)request{
    if(!request.isActive){
        UIView *view = [[UIApplication sharedApplication].delegate window];
        [AlertUtils showHudInView:view hint:nil];  
    }
    NSMutableDictionary *dic;
    if(request.paramter){
        dic = request.paramter.mutableCopy;
    }else{
        dic = [NSMutableDictionary dictionary];
    }
    if(request.style == Request_POST){
        [dic setObject:[userDefaults objectForKey:@"admin_id"] forKey:@"admin_id"];
        [dic setObject:[userDefaults objectForKey:@"guid"] forKey:@"guid"];
    }else if (request.style == Request_GET){
       
    }
  
    [dic setObject:[ToolClass getData] forKey:@"time"];
    NSString *token = [ToolClass gettoken:dic];
    [dic setObject:token forKey:@"authKey"];
    request.paramter = dic;
    
    request.requstUrl = [NSString stringWithFormat:@"%@%@",APP_HOST_ADDRESS,request.requstUrl];
    
    if(request.imgData && request.fileName){
        [self uploadImage:request];
        return;
    }
     [self postRequest:request];
}

- (void)uploadImage:(PPHttpRequest *)request{
    [_sessionManager POST:request.requstUrl parameters:request.paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传文件  服务器对应[file]
        NSArray *imgarr = request.imgData;
        for (UIImage *uploadImage in imgarr) {
            NSData *imageData = UIImageJPEGRepresentation(uploadImage,1);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"HLB%@.jpg",str];
            [formData appendPartWithFileData:imageData name:request.fileName  fileName:fileName mimeType:@"image/jpg"];       // 上传图片的参数key
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AlertUtils hideHud];
        //请求成功返回
        request.response.obj = responseObject;
        int retCode = request.response.code =  [responseObject[@"code"] intValue];
        request.response.msg = responseObject[@"message"];
        
        //  debugLog(@"结果:%@",responseObject);
        if (0 == retCode) {//成功
            if (request.success) {
                request.response.code = retCode;
                request.success(request,request.response.obj[@"data"]);
            }
            
        }else{//失败
            if(ErrorCode01 == retCode){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Login" object:nil userInfo:nil];
            }
            NSString *errorStr= responseObject[@"message"];
            if([errorStr rangeOfString:@"未登录"].location !=NSNotFound)
            {
                NSNotification *ntf = [NSNotification notificationWithName:@"login" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter] postNotification:ntf];
                
            }
            request.failure(request,errorStr);
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AlertUtils hideHud];
        //请求超时
        debugLog(@"请求报错:%@",error.description);
        debugLog(@"Error: %@", error);
        request.response.msg = @"请求数据失败";
        request.response.code = [@"998" intValue];
        request.failure(request,request.response.msg);
        
    }];

}

- (void)postRequest:(PPHttpRequest *)request{
    
    [_sessionManager POST:request.requstUrl parameters:request.paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AlertUtils hideHud];
        //请求成功返回
        request.response.obj = responseObject;
        int retCode = request.response.code =  [responseObject[@"code"] intValue];
        request.response.msg = responseObject[@"message"];
        
        //  debugLog(@"结果:%@",responseObject);
        if (0 == retCode) {//成功
            if (request.success) {
                request.response.code = retCode;
                request.success(request,request.response.obj[@"data"]);
            }
            
        }else{//失败
            if(ErrorCode01 == retCode){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"Login" object:nil userInfo:nil];
            }
            NSString *errorStr= responseObject[@"message"];
            if([errorStr rangeOfString:@"未登录"].location !=NSNotFound)
            {
                NSNotification *ntf = [NSNotification notificationWithName:@"login" object:nil userInfo:nil];
                [[NSNotificationCenter defaultCenter] postNotification:ntf];
                
            }
            request.failure(request,errorStr);
        
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AlertUtils hideHud];
        //请求超时
        debugLog(@"请求报错:%@",error.description);
        debugLog(@"Error: %@", error);
        request.response.msg = @"请求数据失败";
        request.response.code = [@"998" intValue];
        request.failure(request,request.response.msg);

    }];
    
}


- (void)getRequest:(PPHttpRequest *)request{
    
    [_sessionManager GET:request.requstUrl parameters:request.paramter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


@end
